package com.bruce.demo2.patterns.demo1.creational.demo02.factoryMethod.demo4;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @PROJECT_NAME design_patterns
 * @DESCRIPTION 简单工厂的升级（模式扩展）
 * <p>
 * 简单工厂如果添加新的咖啡类型就需要修改简单工厂，如何处理呢？通过配置文件反射方式进行扩展
 * @AUTHOR CNBruceLee
 * @DATE 2021/7/10 18:19
 */
public class SimpleCoffeeFactory {
    //map中可以存类的全路径，也可以直接存放反射实例化的类
    private static Map<String, String> coffeeMap = new HashMap<String, String>();

    static {
        //通过静态代码块导入配置文件
        Properties properties = new Properties();
        InputStream inputStream = SimpleCoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");

        try {
            properties.load(inputStream);
            Set<Object> keys = properties.keySet();
            for (Object key : keys) {
                String className = properties.getProperty((String) key);
                coffeeMap.put((String) key, className);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static Coffee createCoffee(String type) throws Exception {
        Coffee coffee = null;
        //生产咖啡
        Map<String, String> coffeeMap = SimpleCoffeeFactory.coffeeMap;
        if (SimpleCoffeeFactory.coffeeMap.containsKey(type)) {
            String className = coffeeMap.get(type);
            Class clazz = Class.forName(className);
            coffee = (Coffee) clazz.newInstance();
        } else {
            throw new RuntimeException("对不起你点的咖啡没有了");
        }

        return coffee;
    }
}
